var api = require('../config/api.js');

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封装微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Nideshop-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log("success");

        if (res.statusCode == 200) {

          if (res.data.errno == 401) {
            var userInfo = {
              nickName: '点击去登录',
              userName: 'Hi,小主',
              avatarUrl: 'https://hahanongjiang.oss-cn-qingdao.aliyuncs.com/hahanongjiang/icon/miniprogram/default_head.png'
            };
            var token = '';
            wx.setStorageSync('userInfo', userInfo);
            wx.setStorageSync('token', token);
            //wx.removeStorageSync('userInfo');
            //wx.removeStorageSync('token');
            //需要登录后才可以操作
            wx.showModal({
                title: '',
                content: '请先登录',
                success: function (res){
                    if (res.confirm) {
                        wx.switchTab({
                            url: '/pages/ucenter/index/index'
                        });
                    }
                }
            });
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
        reject(err)
        console.log("failed")
      }
    })
  });
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          console.log(res)
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}

function showSuccessToast(msg) {
  wx.showToast({
    title: msg,
  })
}
//文件上传
function uploadimg(data) {
  return new Promise(function (resolve, reject) {
    var that = this,
    i = data.i ? data.i : 0,//当前上传的哪张图片
    success = data.success ? data.success : 0,//上传成功的个数
    fail = data.fail ? data.fail : 0,//上传失败的个数
    resultObject = [];
    wx.uploadFile({
      url: api.SysUpload,
      filePath: data.path[i],
      name: 'file',//这里根据自己的实际情况改
      formData: {
        "commentid": data.commentid,
        "sortorder": i+1,
      },//这里是上传图片时一起上传的数据
      success: (resp) => {
        console.log("上传结果通知",resp);
        if (JSON.parse(resp.data).errno == 0) {
          success++;//图片上传成功，图片上传成功的变量+1
        } else {
          fail++;//图片上传失败，图片上传失败的变量+1
        }
      },
      fail: (res) => {
        fail++;//图片上传失败，图片上传失败的变量+1
      },
      complete: () => {
        i++;//这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) {   //当图片传完时，停止调用
          resolve(i);
          console.log('执行完毕,成功：' + success + " 失败：" + fail);
        } else {//若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          uploadimg(data).then(function(e){
            resolve(e);
          });
        }
      }
    });
  })
}

module.exports = {
  formatTime,
  request,
  redirect,
  showErrorToast,
  showSuccessToast,
  checkSession,
  login,
  uploadimg,
}


